package ar.com.bdf.ipharma.stress;

import java.util.ArrayList;
import java.util.List;

import ar.com.bdf.ipharma.communications.serial.BasicWritePort;
import ar.com.bdf.ipharma.protocolo.model.HandShake;
import ar.com.bdf.ipharma.protocolo.model.ParserTrama;

public class Task {

	private String port;
	private Long timeInterOperation;
	private List<Operation> operations = new ArrayList<Operation>();
	private Integer identificador = 1;
	
	public Integer getIdentificador() {
		return identificador;
	}

	public void setIdentificador(Integer identificador) {
		this.identificador = identificador;
	}

	public List<Operation> getOperations() {
		return operations;
	}

	public void setOperations(List<Operation> operations) {
		this.operations = operations;
	}

	public String getPort() {
		return port;
	}

	public void setPort(String port) {
		this.port = port;
	}

	public Long getTimeInterOperation() {
		return timeInterOperation;
	}

	public void setTimeInterOperation(Long timeInterOperation) {
		this.timeInterOperation = timeInterOperation;
	}

	public void execute() {
		for (Operation operation : operations) {
			operation.setIdentificador(identificador);
			for (int i = 1; i <= operation.getCountOperation(); i++) {
				HandShake handshake = operation.getHandShake();
				if (handshake != null){
					String serializable = getParser().serializable(handshake.getRequest());
					sendByCom(serializable);
					dormir();
				}
			}
		}

	}

	private ParserTrama getParser() {
		return new ParserTrama();
	}

	private void dormir() {
		try {
			System.out.println("sleeping...");
			Thread.sleep(timeInterOperation * 1000L);
		} catch (Exception e) {
			System.out.println("No se pudo dormir " + timeInterOperation + " segundos");
			e.printStackTrace();
		}
	}

	private void sendByCom(String serializable) {
		try {
			System.out.print(port + "===> " + serializable);

			BasicWritePort handler = new BasicWritePort(port);
			System.out.println("String serialiado :" + serializable);
			System.out.println("Se escribira en el puerto....");
			handler.write(serializable);
			System.out.println("Se cerrara la conexion");
			handler.close();
			System.out.println("conexion cerrada");
		} catch (Exception e) {
			System.out.println("EXCEPCION SENDBYCOM :" + e.getMessage());
		}
	}
}
